package com.daoImpl;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.hibernate.LockMode;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.bean.Craft;
import com.bean.CraftShow;
import com.dao.CraftDao;

/**
 * A data access object (DAO) providing persistence and search support for Craft
 * entities. Transaction control of the save(), update() and delete() operations
 * can directly support Spring container-managed transactions or they can be
 * augmented to handle user-managed Spring transactions. Each of these methods
 * provides additional information for how to configure it for the desired type
 * of transaction control.
 * 
 * @see com.bean.Craft
 * @author MyEclipse Persistence Tools
 */
public class CraftDaoImpl extends HibernateDaoSupport implements CraftDao {
	private static final Logger log = LoggerFactory.getLogger(CraftDaoImpl.class);
	// property constants
	public static final String CRAFT_CODE = "craftCode";
	public static final String CRAFT_NAME = "craftName";
	public static final String CRAFT_TYPE_ID = "craftTypeId";
	public static final String GRADE_ID = "gradeId";
	public static final String STD_TIME = "stdTime";
	public static final String OUTPUT = "output";
	public static final String STD_PRICE = "stdPrice";
	public static final String DEMAND = "demand";
	public static final String COUNT = "count";
	public static final String MEMO = "memo";

	protected void initDao() {
		// do nothing
	}

	/* (non-Javadoc)
	 * @see com.daoImpl.CraftDao#save(com.bean.Craft)
	 */
	@Override
	public void save(Craft transientInstance) {
		log.debug("saving Craft instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.daoImpl.CraftDao#delete(com.bean.Craft)
	 */
	@Override
	public void delete(Craft persistentInstance) {
		log.debug("deleting Craft instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.daoImpl.CraftDao#findById(java.lang.Integer)
	 */
	@Override
	public Craft findById(java.lang.Integer id) {
		log.debug("getting Craft instance with id: " + id);
		try {
			Craft instance = (Craft) getHibernateTemplate().get(
					"com.bean.Craft", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.daoImpl.CraftDao#findByExample(com.bean.Craft)
	 */
	@Override
	public List findByExample(Craft instance) {
		log.debug("finding Craft instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.daoImpl.CraftDao#findByProperty(java.lang.String, java.lang.Object)
	 */
	@Override
	public List findByProperty(String propertyName, Object value) {
		log.debug("finding Craft instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from Craft as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.daoImpl.CraftDao#findByCraftCode(java.lang.Object)
	 */
	@Override
	public List findByCraftCode(Object craftCode) {
		return findByProperty(CRAFT_CODE, craftCode);
	}

	/* (non-Javadoc)
	 * @see com.daoImpl.CraftDao#findByCraftName(java.lang.Object)
	 */
	@Override
	public List findByCraftName(Object craftName) {
		return findByProperty(CRAFT_NAME, craftName);
	}

	/* (non-Javadoc)
	 * @see com.daoImpl.CraftDao#findByCraftTypeId(java.lang.Object)
	 */
	@Override
	public List findByCraftTypeId(Object craftTypeId) {
		return findByProperty(CRAFT_TYPE_ID, craftTypeId);
	}

	/* (non-Javadoc)
	 * @see com.daoImpl.CraftDao#findByGradeId(java.lang.Object)
	 */
	@Override
	public List findByGradeId(Object gradeId) {
		return findByProperty(GRADE_ID, gradeId);
	}

	/* (non-Javadoc)
	 * @see com.daoImpl.CraftDao#findByStdTime(java.lang.Object)
	 */
	@Override
	public List findByStdTime(Object stdTime) {
		return findByProperty(STD_TIME, stdTime);
	}

	/* (non-Javadoc)
	 * @see com.daoImpl.CraftDao#findByOutput(java.lang.Object)
	 */
	@Override
	public List findByOutput(Object output) {
		return findByProperty(OUTPUT, output);
	}

	/* (non-Javadoc)
	 * @see com.daoImpl.CraftDao#findByStdPrice(java.lang.Object)
	 */
	@Override
	public List findByStdPrice(Object stdPrice) {
		return findByProperty(STD_PRICE, stdPrice);
	}

	/* (non-Javadoc)
	 * @see com.daoImpl.CraftDao#findByDemand(java.lang.Object)
	 */
	@Override
	public List findByDemand(Object demand) {
		return findByProperty(DEMAND, demand);
	}

	/* (non-Javadoc)
	 * @see com.daoImpl.CraftDao#findByCount(java.lang.Object)
	 */
	@Override
	public List findByCount(Object count) {
		return findByProperty(COUNT, count);
	}

	/* (non-Javadoc)
	 * @see com.daoImpl.CraftDao#findByMemo(java.lang.Object)
	 */
	@Override
	public List findByMemo(Object memo) {
		return findByProperty(MEMO, memo);
	}

	/* (non-Javadoc)
	 * @see com.daoImpl.CraftDao#findAll()
	 */
	@Override
	public List findAll() {
		log.debug("finding all Craft instances");
		try {
			String queryString = "from Craft";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.daoImpl.CraftDao#merge(com.bean.Craft)
	 */
	@Override
	public Craft merge(Craft detachedInstance) {
		log.debug("merging Craft instance");
		try {
			Craft result = (Craft) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.daoImpl.CraftDao#attachDirty(com.bean.Craft)
	 */
	@Override
	public void attachDirty(Craft instance) {
		log.debug("attaching dirty Craft instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.daoImpl.CraftDao#attachClean(com.bean.Craft)
	 */
	@Override
	public void attachClean(Craft instance) {
		log.debug("attaching clean Craft instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	/**
	 * 
	 */
	public List<CraftShow> getFindCraft(String table,String pk,String sort,int PageNumber,int PageSize ,String options){
		Session session = getSession();  
		SQLQuery query=null;
		
		StringBuffer sqlbuf = new StringBuffer("execute [dbo].[sp_get_page_of_table] ");
		sqlbuf.append("'"+table+"','"+pk+"','"+sort+"',"+PageNumber+","+PageSize+",'*',\""+options+"\"");
		
		query=session.createSQLQuery(sqlbuf.toString());
		
		List<Object[]> resultSet = query.list();
		List<CraftShow> list = new ArrayList<CraftShow>();
		for (Object[] r : resultSet) {
			
			CraftShow cs = new CraftShow();
		
			cs.setCraftId((Integer)r[0]);
			cs.setCraftCode((String)r[1]);
			cs.setCraftName((String)r[2]);
			cs.setCraftTypeId((Integer)r[3]);
			cs.setGradeId((Integer)r[4]);
			cs.setStdTime((Double)r[5]);
			cs.setOutput((Double)r[6]);
			cs.setStdPrice((Double)r[7]);
			cs.setDemand((String)r[8]);
			cs.setCount((Integer)r[9]);
			cs.setMemo((String)r[10]);
			cs.setWage((Double)r[11]);
			cs.setUnit((String)r[12]);
			cs.setUpdateTime((Timestamp)r[13]);
			cs.setGradeName((String)r[14]);
			cs.setTypeName((String)r[15]);
			
			list.add(cs);
		}
		
		return list;
	}
	
	
	/**
	 * 获取编码
	 * @return
	 */
	public String getCodeByType(int craftType){
		Session session = getSession();  
		SQLQuery query=null;
		StringBuffer sqlbuf = new StringBuffer("execute [audit].[sp_get_craft_code] ");
		sqlbuf.append("@craft_type="+craftType);
		
		query=session.createSQLQuery(sqlbuf.toString());
		String craftCode = null;
		List resultSet = query.list();
		
		craftCode = (String)resultSet.get(0);
		
		return craftCode;
		
	}
	
	/**
	 * 根据id获取信息
	 * @param ctx
	 * @return
	 */
	public CraftShow findByCraft(int craftId){
		
		Session session = getSession();  
		SQLQuery query=null;
		String sql = "SELECT c.craft_id,c.craft_code,c.craft_name,c.craft_type_id,c.grade_id,c.std_time,c.[output],c.std_price,c.demand,c.[count],c.memo,g.wage,g.unit,g.update_time,g.grade_name,t.type_name "
				+ "FROM audit.craft c INNER JOIN audit.craft_grade g ON c.grade_id = g.grade_id INNER JOIN audit.craft_type t ON c.craft_type_id = t.craft_type_id where c.craft_id=:craftId";
		
		
		query=session.createSQLQuery(sql);
		query.setInteger("craftId", craftId);
		
		List<Object[]> resultSet = query.list();
		
		CraftShow cs = new CraftShow();
		
		for (Object[] r : resultSet) {
			cs.setCraftId((Integer)r[0]);
			cs.setCraftCode((String)r[1]);
			cs.setCraftName((String)r[2]);
			cs.setCraftTypeId((Integer)r[3]);
			cs.setGradeId((Integer)r[4]);
			cs.setStdTime((Double)r[5]);
			cs.setOutput((Double)r[6]);
			cs.setStdPrice((Double)r[7]);
			cs.setDemand((String)r[8]);
			cs.setCount((Integer)r[9]);
			cs.setMemo((String)r[10]);
			cs.setWage((Double)r[11]);
			cs.setUnit((String)r[12]);
			cs.setUpdateTime((Timestamp)r[13]);
			cs.setGradeName((String)r[14]);
			cs.setTypeName((String)r[15]);
			
		}
		
		return cs;
		
	}
	
	public static CraftDao getFromApplicationContext(ApplicationContext ctx) {
		return (CraftDao) ctx.getBean("CraftDaoImpl");
	}
}